import json
from datetime import datetime

from django.core.paginator import Paginator
from django.http import JsonResponse
from django.views import View

from menu.models import SysRoleMenu
from role.models import SysRole, SysRoleSerializer, SysUserRole


# Create your views here.
# 查询所有角色信息
class ListView(View):

    def get(self, request):
        obj_roleList = SysRole.objects.all().values()  # 转成字典
        roleList = list(obj_roleList)  # 把外层的容器转为List
        return JsonResponse({'code': 200, 'roleList': roleList})


# 角色信息查询
class SearchView(View):

    def post(self, request):
        data = json.loads(request.body.decode("utf-8"))
        pageNum = data['pageNum']  # 当前页
        pageSize = data['pageSize']  # 每页大小
        query = data['query']  # 查询参数
        roleListPage = Paginator(SysRole.objects.filter(name__icontains=query), pageSize).page(pageNum)
        # obj_roles = roleListPage.object_list.values()  # 转成字典
        # roles = list(obj_roles)  # 把外层的容器转为List
        total = SysRole.objects.filter(name__icontains=query).count()
        role_list = []
        for role in roleListPage:
            userRoles = SysUserRole.objects.all().filter(role=role)
            role_list.append({
                'id': role.id,
                'name': role.name,
                'code': role.code,
                'status': role.status,
                'user_count': len(userRoles),  # 计算关联的资源数量
                'create_time': role.create_time,
                'update_time': role.update_time,
                'remark': role.remark,
            })
        return JsonResponse({'code': 200, 'roleList': role_list, 'total': total})


class SaveView(View):

    def post(self, request):
        data = json.loads(request.body.decode("utf-8"))
        if data['id'] == -1:  # 添加

            try:
                if SysRole.objects.get(name=data['name']):
                    return JsonResponse({'code': 500, 'msg': '已经存在相同名称的角色！'})
            except SysRole.DoesNotExist:
                pass  # 没有找到则继续后续逻辑

            try:
                if SysRole.objects.get(code=data['code']):
                    return JsonResponse({'code': 500, 'msg': '已经存在相同名称的角色！'})
            except SysRole.DoesNotExist:
                pass  # 没有找到则继续后续逻辑

            obj_sysRole = SysRole(name=data['name'], status=data['status'], code=data['code'], remark=data['remark'])
            obj_sysRole.create_time = datetime.now().date()
            obj_sysRole.save()
        else:  # 修改
            obj_sysRole = SysRole(id=data['id'], name=data['name'], status=data['status'], code=data['code'],
                                  remark=data['remark'], create_time=data['create_time'],
                                  update_time=data['update_time'])
            obj_sysRole.update_time = datetime.now().date()
            obj_sysRole.save()
        return JsonResponse({'code': 200})


# 角色基本操作
class ActionView(View):

    def get(self, request):
        """
        根据id获取角色信息
        :param request:
        :return:
        """
        id = request.GET.get("id")
        role_object = SysRole.objects.get(id=id)
        return JsonResponse({'code': 200, 'role': SysRoleSerializer(role_object).data})

    def delete(self, request):
        """
        删除操作
        :param request:
        :return:
        """
        idList = json.loads(request.body.decode("utf-8"))
        SysUserRole.objects.filter(role_id__in=idList).delete()
        SysRoleMenu.objects.filter(role_id__in=idList).delete()
        SysRole.objects.filter(id__in=idList).delete()
        return JsonResponse({'code': 200})


# 根据角色查询菜单权限
class MenusView(View):

    def get(self, request):
        id = request.GET.get("id")
        menuList = SysRoleMenu.objects.filter(role_id=id).values("menu_id")
        menuIdList = [m['menu_id'] for m in menuList]
        return JsonResponse(
            {'code': 200, 'menuIdList': menuIdList})


# 角色权限授权
class GrantMenu(View):

    def post(self, request):
        data = json.loads(request.body.decode("utf-8"))
        role_id = data['id']
        menuIdList = data['menuIds']
        SysRoleMenu.objects.filter(role_id=role_id).delete()  # 删除角色菜单关联表中的指定角色数据
        for menuId in menuIdList:
            roleMenu = SysRoleMenu(role_id=role_id, menu_id=menuId)
            roleMenu.save()
        return JsonResponse({'code': 200})


# 状态修改
class StatusView(View):

    def post(self, request):
        data = json.loads(request.body.decode("utf-8"))
        id = data['id']
        status = data['status']
        role_object = SysRole.objects.get(id=id)
        role_object.status = status
        role_object.save()
        return JsonResponse({'code': 200})
